from cash_pos.constants.common_sequence import SWITCH_ENV

from appium.webdriver.common.appiumby import AppiumBy
import logging

from appium.webdriver.webdriver import WebDriver

from cash_pos.constants.common_sequence import CouponTabCons
from cash_pos.function.common_function import CommonFunction
from cash_pos.page.pay_page.pay_out_page import PayOutPage

logger = logging.getLogger(__name__)

"""
Description:
关于优惠券相关的页面，在这里我把它归结到了涉及安全的文件夹
"""


class CouponSearchPage(object):

    def __init__(self, client):
        self.client = client
        self.driver: WebDriver = client.driver
        self.width = client.width
        self.height = client.height

    """
    Service Function
    """

    def screen_shoot(self, filename, path):
        """
        屏幕截图
        Params:
        -filename:文件名称
        -path:路径
        """
        CommonFunction(self.driver).screen_shoot(filename=filename, path=path)
        try:
            self.driver.find_element(AppiumBy.XPATH, f'//android.widget.TextView[@resource-id="{SWITCH_ENV}:id/tv_confirm"]').click()
        except Exception:
            raise Exception("没有可以使用的优惠券！")
        return self

    def get_coupon_first(self):
        """
        获取优惠券(默认选择第一个优惠券进行选择)
        """
        target_elements = self.driver.find_elements(AppiumBy.ID, f'{SWITCH_ENV}:id/cb_select')
        target_elements[0].click()
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/tv_confirm').click()
        return PayOutPage(self.client)

    def get_coupon(self, name: str):
        """
        获取优惠券（默认滚动50次）
        Params:
        -name:优惠券名称（要传递有标识性的名称或者全称）
        """
        tv_frame_element = self.driver.find_element(AppiumBy.XPATH,
                                                    f'//android.widget.TextView[@resource-id="{SWITCH_ENV}:id/tv_title"]/..')
        height = int(tv_frame_element.size['height'])

        break_tag = False
        for num in range(50):
            coupon_items = self.driver.find_elements(AppiumBy.ID, f'{SWITCH_ENV}:id/tv_name')
            cb_select_list = self.driver.find_elements(AppiumBy.ID, f'{SWITCH_ENV}:id/cb_select')
            for record in coupon_items:
                if name.strip() in record.text.strip():
                    coupon_index = coupon_items.index(record)
                    cb_select_list[coupon_index].click()
                    break_tag = True
                    break
            if break_tag:
                break
            self.driver.swipe(start_x=self.width / 2, start_y=self.height / 2, end_x=self.width / 2,
                              end_y=(self.height / 2 - 2 * height / 9), duration=250)
        if break_tag is False:
            # 取消
            self.cancel_button()
            raise Exception("优惠券未找到")
        self.driver.find_element(AppiumBy.XPATH, f'//android.widget.TextView[@resource-id="{SWITCH_ENV}:id/tv_confirm"]').click()
        return PayOutPage(self.client)

    """
    Button Function
    """

    def select_tab(self, tab_name):
        """
        切换tab页
        -tab_name:页名称
        """
        if tab_name == CouponTabCons.available.value:
            self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/ll_available_title').click()
        elif tab_name == CouponTabCons.expired.value:
            self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/ll_expiped_title').click()
        elif tab_name == CouponTabCons.disabled.value:
            self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/ll_voided_title')
        return self

    def confirm_button(self):
        """
        确认按钮
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/ll_confirm').click()
        return self

    def cancel_button(self):
        """
        取消按钮
        """
        self.driver.find_element(AppiumBy.ID, f'{SWITCH_ENV}:id/ll_cancel').click()
        return self
